﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Orleans;
using Orleans.Hosting;
using Orleans.Providers;
using Orleans.Runtime;
using Orleans.Storage;

namespace iTool.ClusterComponent
{
    public static class iToolStorageBuilderExtensions
    {
        /// <summary>
        /// 指定默认存储方式
        /// </summary>
        public static ISiloHostBuilder UseiToolStorageAsDefault(this ISiloHostBuilder builder)
        {
            return builder.UseiToolStorage(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME);
        }

        /// <summary>
        /// 给指定Title指定
        /// </summary>
        /// <returns></returns>
        public static ISiloHostBuilder UseiToolStorage(this ISiloHostBuilder builder, string name)
        {
            return builder.ConfigureServices(services => services.UseiToolStorage(name));
        }

        /// <summary>
        /// 给指定Title指定
        /// </summary>
        /// <returns></returns>
        internal static IServiceCollection UseiToolStorage(this IServiceCollection services, string name)
        {
            services.TryAddSingleton(sp => sp.GetServiceByName<IGrainStorage>(ProviderConstants.DEFAULT_STORAGE_PROVIDER_NAME));
            services.AddSingletonNamedService(name, new iToolStorageFactory().Create);
            services.AddSingletonNamedService(name, (s, n) => (ILifecycleParticipant<ISiloLifecycle>)s.GetRequiredServiceByName<IGrainStorage>(n));
            return services;
        }
    }
}
